CREATE PROCEDURE [dbo].[bd_proc_leaveDeductJob]
  @beginDate AS DATE,
  @endDate AS DATE
AS
BEGIN

		--  异常扑捉机制
		BEGIN TRY
			BEGIN TRAN
			--待扣除的人员名单和对应的值
			create table #leave_deduct(
				user_serial bigint not null,
				deduct_value int DEFAULT 0
			)
			--关联请假单和请假明细表，条件：审批通过的单子，明细表中有效状态为有效，请假日期在@beginDate，@endDate之间，是否已扣除为null
		--统计每人的总时长
		insert into #leave_deduct
		select x.user_serial,sum(x.jsjg) as deduct_value from (
			select l.user_serial,jsjg from lr_kqingj l
			INNER JOIN bd_leave_order b on b.order_id = l.order_id

			where b.status in (3,4) and l.whether_validity = 1

			and l.is_deduct is null
			and l.bh = '00105'
			and l.kssj between @beginDate and @endDate) x GROUP BY x.user_serial

		--扣除使用
		update n
			set n.real_txts = n.real_txts - t.deduct_value
		from bd_nianjia n
		INNER JOIN #leave_deduct t on n.user_serial = t.user_serial

		--给明细记录打标机
		update l
				set is_deduct = '1'
			from lr_kqingj l
			INNER JOIN bd_leave_order b on b.order_id = l.order_id

			where b.status in (3,4) and l.whether_validity = 1

			and l.is_deduct is null
			and l.bh = '00105'
			and l.kssj between @beginDate and @endDate

			--  提交事务
			COMMIT TRAN

		--  结束异常捕捉
		END TRY

		BEGIN CATCH
			DECLARE @errStr VARCHAR(MAX) = ERROR_MESSAGE();
			IF XACT_STATE() <> 0
			BEGIN
			  ROLLBACK TRANSACTION;
			  RAISERROR (@errStr, 16, 1);
			END;
		END CATCH
END